{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 贪心算法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 概览\n",
    "\n",
    "- 贪心算法是近似算法，易于实现，运行速度快。\n",
    "- 贪心算法寻找局部最优解，企图以这种方式获得全局最优解。\n",
    "- 对于Np完全问题还没有找到快速解决方案，最佳的做法就是使用近似算法。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 集合覆盖问题代码实现"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-12-29T16:45:38.509597Z",
     "start_time": "2018-12-29T16:45:38.490886Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'kthree', 'kfive', 'kone', 'ktwo'}\n"
     ]
    }
   ],
   "source": [
    "# 要覆盖的州\n",
    "states_needed = set(['mt', 'wa', 'or', 'id', 'nv',\n",
    "                    'ut', 'ca', 'az'])\n",
    "\n",
    "# 广播台清单\n",
    "stations = {}\n",
    "stations['kone'] = set(['id', 'nv', 'ut'])\n",
    "stations['ktwo'] = set(['wa', 'id', 'mt'])\n",
    "stations['kthree'] = set(['or', 'nv', 'ca'])\n",
    "stations['kfour'] = set(['nv', 'ut'])\n",
    "stations['kfive'] = set(['ca', 'az'])\n",
    "\n",
    "# 存放最终选择的广播台\n",
    "final_stations = set()\n",
    "# 每次寻找局部最优\n",
    "while states_needed:\n",
    "    states_covered = set()\n",
    "    best_station = None\n",
    "    for station, state_for_station in stations.items():\n",
    "        covered = state_for_station & states_needed\n",
    "        if len(covered) > len(states_covered):\n",
    "            best_station = station\n",
    "            states_covered = covered\n",
    "    states_needed -= states_covered\n",
    "    final_stations.add(best_station)\n",
    "    \n",
    "print(final_stations)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.7"
  },
  "toc": {
   "nav_menu": {},
   "number_sections": false,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
